#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vi: ts=4 expandtab
#
# Copyright (C) 2012 KT
#
# Author: Choonho Son <choonho.son@kt.com>
#

__version__="1.0"

import sys
import platform
import os.path


class Cmd:
	"""
	default class
	"""
	# key   : os
	# value : (query, installer)
	__PKG__ = {'CentOS' : (['rpm','-qa'], ['yum','-y', 'install']),
		   'redhat' : (['rpm','-qa'], ['yum','-y', 'install']),
		   }
	
	def __init__(self, logger):
		self.logger = logger
		self.OS = self.checkOS()
		
	def run(self, cmd, shell=False):
		import subprocess
		import traceback
		try:
			proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=shell)
			out,err = proc.communicate()
			self.logger.debug("OUT:%s" % out)
			self.logger.debug("ERR:%s" % err)
			return (out,err)

		except:
			self.logger.debug(traceback.format_exc())
			raise Exception("Cmd failed %s" % cmd)

	def checkOS(self):
		if sys.version_info < (2,6):
			(OS,ver,id) = platform.dist()
		else:
			(OS,ver,id) = platform.linux_distribution()
		return OS
	
	def isInstalledPackage(self, name):
		"""
		check Package is installed or not
		@param name : package name
		@return : True/False
		"""
		cmd = self.__PKG__[self.OS][0] + [name]
		(out, err) = self.run(cmd)
		self.logger.debug("isInstalledPackage:%s" % out)

		if out:
			return True
		return False

	def installPackage(self, names):
		pkgs = names.split(",")
		for name in pkgs:
			self.logger.debug("pkg query:%s" % name)
			self.isInstalledPackage(name)
			#if self.isInstalledPackage(name) == True:
			#	continue
			#self.logger.debug("Need Install pkg:%s" % name)
			cmd = self.__PKG__[self.OS][1] + [name]
			(out, err) = self.run(cmd)
		
	def service(self, svc, action='restart'):
		"""
		start service daemon
		@param svc : service name
		"""
		cmd = ["service",svc,action]
		return self.run(cmd)

	def addService(self, svc):
		"""
		add service in rc
		ex) chkconfig svc on
		"""
		cmd = ["chkconfig",svc, "on"]
		return self.run(cmd)
	
	def isExist(self, path):
		return os.path.exists(path)
	
	def rm(self, path):
		"""
		rm path
		"""
		cmd = ["rm",path]
		return self.run(cmd)

	def rmdir(self, path):
		cmd = ["rm","-rf",path]
		return self.run(cmd)
	
	def copy(self, src, dst):
		"""
		copy file from src to dst
		"""
		cmd = ["cp","-f",src,dst]
		return self.run(cmd)

	def chown(self, path, user, group, recursive=False):
		"""
		chown user:group path
		if recursive == True
		chown -R user:group path
		"""
		if recursive == True:
			cmd = ["chown","-R","%s:%s" % (user,group) ,path]
		else:
			cmd = ["chown","%s:%s" % (user,group) ,path]

		return self.run(cmd)
